﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;

/*
 * TH07 Groep 10
 * ----------------------------------------------------------------------------------
 * Versie   Door        Commentaar
 * 0.1      Luca        Opzet en programmeer werk
 * 0.2      Erwin       Verplaatst naar Algorithms,
 *                      aangepast om als reference te gebruiken
 */

namespace THO7_Team8.Filters
{
	/// <summary>
	/// Klasse om het algoritme uit te voeren om een afbeelding binair te maken.
	/// </summary>
	public class Binair
	{
		public static Bitmap RunBitmapAlgorithm(Bitmap source)
		{
			int _width = source.Width;
			int _height = source.Height;

			Bitmap binairImage = new Bitmap(_width, _height);
			BitmapData binairData = binairImage.LockBits
				(new Rectangle(0, 0, _width, _height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);

			BitmapData sourceData = source.LockBits
				(new Rectangle(0, 0, _width, _height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

			unsafe
			{
				byte* srcPointer = (byte*) sourceData.Scan0;
				byte* binPointer = (byte*) binairData.Scan0;

				int total = sourceData.Stride * _height;

				for(int i = 0; i < total; i += 3)
				{
					if(srcPointer[i] < 60 && srcPointer[i + 1] > 120 && srcPointer[i + 2] > 190)
					{ //wit maken
						binPointer[i] = 255;
						binPointer[i + 1] = 255;
						binPointer[i + 2] = 255;
					}
					else
					{ //zwart maken
						binPointer[i] = 0;
						binPointer[i + 1] = 0;
						binPointer[i + 2] = 0;
					}
				}
				source.UnlockBits(sourceData);
				binairImage.UnlockBits(binairData);
			}
			return binairImage;
		}

		public static byte[] RunArrayAlgorithm(Bitmap source)
		{
			int _width = source.Width;
			int _height = source.Height;
			BitmapData sourceData = source.LockBits
				(new Rectangle(0, 0, _width, _height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
			byte[] binairImage;

			unsafe
			{
				byte* srcPointer = (byte*) sourceData.Scan0;

				int total = sourceData.Stride * _height;
				binairImage = new byte[total];

				for(int i = 0; i < total; i += 3)
				{
					if(srcPointer[i] < 60 && srcPointer[i + 1] > 120 && srcPointer[i + 2] > 190)
					{ //wit maken
						binairImage[i] = 255;
						binairImage[i + 1] = 255;
						binairImage[i + 2] = 255;
					}
					else
					{ //zwart maken
						binairImage[i] = 0;
						binairImage[i + 1] = 0;
						binairImage[i + 2] = 0;
					}
				}
				source.UnlockBits(sourceData);
			}
			return binairImage;
		}
	}
}